package com.example.demo.controller;

import com.example.demo.common.JwtUtils;
import com.example.demo.common.ResultModel;
import com.example.demo.common.ResultModelTool;
import com.example.demo.entity.RoomPicture;
import com.example.demo.entity.User;
import com.example.demo.service.PictureService;
import com.example.demo.service.RoomPictureService;
import com.example.demo.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.validation.constraints.Positive;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@CrossOrigin
@RequestMapping("/room_pictures")
public class RoomPictureController {
        @Resource
      RoomPictureService roomPictureService;
     //static String fileLocation = "/restaurantRes/";//图片资源访问路径

   static String fileLocation = "/static/restaurantRes/";//图片资源访问路径
    //存储预返回页面的结果对象
    private Map<String, Object> result = new HashMap<>();
    //注入业务对象
    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private JwtUtils jwtUtils;
    /**
     * 房间图片查询
     * @param picture_room_no
     * @return
     */
    @GetMapping(value = "/search/{picture_room_no}")
    @ResponseBody
    public ResultModel selectroompictures(@PathVariable(value = "picture_room_no")@Positive(message = "{picture_room_no}")int picture_room_no){

        ResultModel resultModel = new ResultModel();
        resultModel.setCode(200);
        resultModel.setData(roomPictureService.selectroompictures(picture_room_no));
        return ResultModelTool.handleResultModel(resultModel);
    }

    /*
     * 图片新增
     * */
    @PostMapping("")
    @ResponseBody
    public ResultModel uploadFood(int picture_room_no, Part pictureFile,
                                  HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(token);
        String userId = claims.getId();
        User user1=userService.getUser(userId);
        if(user1==null){
            return new ResultModel(200,"token过期或者权限不足");
        }


        Map<String, Object> result= new HashMap<String,Object>();
        //获取提交文件名称
        String filename = pictureFile.getSubmittedFileName();
        String newfilename=System.currentTimeMillis()+ UUID.randomUUID().toString().replace(".","").substring(0,6)+"."+filename.substring(filename.lastIndexOf(".")+1);

        //定义上传文件存放的路径
        String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
        System.out.println(path);
        //返回保存的url，根据url可以进行文件查看或者下载
        String filePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() //端口 https443端口无需添加
                + fileLocation + newfilename;

        String picture_url = filePath;//根路径+文件名

//插入这条Food数据
        roomPictureService.insert(new RoomPicture(picture_room_no,picture_url));

        //写入文件
        try {
            pictureFile.write(newfilename);
            result.put("Result", "添加图片信息成功");
        } catch (IOException e) {
            e.printStackTrace();
            result.put("Result", "添加图片信息失败");
        }
        ResultModel resultmodel=new ResultModel();
        resultmodel.setCode(200);
        resultmodel.setData(result);
        return ResultModelTool.handleResultModel(resultmodel);
    }

    /*
     * 图片列表
     * */

    @GetMapping("")
    @ResponseBody
    public ResultModel selectAll() {
        List<RoomPicture> list = roomPictureService.list();
        ResultModel resultModel = new ResultModel();
        resultModel.setCode(200);
        resultModel.setData(list);
        return ResultModelTool.handleResultModel(resultModel);

    }


    /*
     * 图片删除（删除路径同时删除文件）
     * */
    @DeleteMapping("/{picture_id}")
    @ResponseBody
    public ResultModel  deleteFile(@PathVariable(value = "picture_id") @Positive(message = "{picture_id}") int picture_id) throws IOException {

        String token = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(token);
        String userId = claims.getId();
        User user1=userService.getUser(userId);
        if(user1==null){
            return new ResultModel(200,"token过期或者权限不足");
        }

        ResultModel resultModel = new ResultModel();
        try {
            String deletePath= pictureService.selectid(picture_id).getPictureFileURL();
            String cc= deletePath.substring(deletePath.lastIndexOf("/")+1);
        //    String truepath="d:/restaurantRes/"+cc;
           String truepath="/static/restaurantRes/"+cc;
            System.out.println(deletePath);
            System.out.println(cc);
            File file=new File(truepath);
            file.delete();
            roomPictureService.delete(picture_id);
            resultModel.setData("删除成功");
            resultModel.setCode(200);
            return ResultModelTool.handleResultModel(resultModel);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        resultModel.setCode(203);//删除失败
        return ResultModelTool.handleResultModel(resultModel);
    }

}
